package com.zkthink.ceres.member.service.impl;

import com.zkthink.base.service.SuperServiceImpl;
import com.zkthink.database.mybatis.conditions.Wraps;
import com.zkthink.ceres.member.dao.MemberAddressMapper;
import com.zkthink.ceres.member.entity.MemberAddress;
import com.zkthink.ceres.member.service.MemberAddressService;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 业务实现类 商城会员收货地址
 * </p>
 *
 * @author kellen
 * @date 2020-05-02
 */
@Slf4j
@Service
public class MemberAddressServiceImpl extends
    SuperServiceImpl<MemberAddressMapper, MemberAddress> implements
    MemberAddressService {

  @Override
  public List<MemberAddress> queryByMid(Long mid) {
    return this.list(Wraps.<MemberAddress>lbQ()
        .eq(MemberAddress::getMid, mid)
        .eq(MemberAddress::getIsDeleted, false)
        .orderByDesc(MemberAddress::getIsDefault).orderByDesc(MemberAddress::getUpdateTime)
    );
  }


  @Override
  @Transactional(rollbackFor = Exception.class)
  public void add(MemberAddress memberAddress) {
    if (memberAddress.getIsDefault()) {
      //查询是否有默认的收货地址
      MemberAddress address = this.queryDefaultAddress(memberAddress.getMid());
      if (address != null) {
        address.setIsDefault(false);
        this.updateById(address);
      }
    }
    this.saveOrUpdate(memberAddress);
  }

  @Override
  public MemberAddress queryDefaultAddress(Long mid) {
    return  this.getOne(
        Wraps.<MemberAddress>lbQ()
            .eq(MemberAddress::getIsDefault, true)
            .eq(MemberAddress::getMid, mid)
    );
  }
}
